<?php

namespace App\Http\Controllers;
use Laravel\Lumen\Routing\Controller as BaseController;
use Illuminate\Http\Request;

// use App\Modules\BaseModule;
use Closure;
use App\Common\Helper;
use App\Common\Http\Result;
use App\Common\Http\Basics\Error;

abstract class Controller extends BaseController
{


    /**
     * @description:
     * @param {string} $msg    返回信息
     * @param {array} $data    数据
     * @param {array} $header  响应头
     * @return {*}
     */
    public final function json(Result  $result)
    {
        return  Helper::toHttpJson( $result );
    }



    /**
     * @description:   对应传进来的类 -> 路由动作的方法名 在 App\Modules\BaseModule 里解析各种参数
     * @param {*} $moduleClass    moudules文件夹里的类
     * @param {Request} $request
     * @param {null} $formatFunc
     * @param {array} $funcParams
     * @return {*}
     */
    public final  function loadModules(string|array $moduleClass, Request $request, Closure|null $formatFunc = null, array $funcParams = [],\Closure|null $afterFunc = null)
    {
        $module = $this->newModule($moduleClass, $request, $formatFunc, $funcParams);

        if($afterFunc !== null ) $afterFunc($module,$request);  //完成操作后回调 可插入日志功能

        return $this->json($module->result);
    }

    private  final function newModule(string|array $moduleClass, Request $request, Closure|null $formatFunc = null, array $funcParams = [])
    {
        if (is_string($moduleClass)) return new $moduleClass($request, $formatFunc, $funcParams);
        else if (array_is_list($moduleClass) && count($moduleClass) === 2) return new $moduleClass[0]($request, $formatFunc, $funcParams, $moduleClass[1]);
        else Helper::throwHttpCustom(Error::MODULE_PARAMS_ERROR);  //填错参数
    }
}
